package com.tanhua.app.service;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.tanhua.api.db.QuestionApi;
import com.tanhua.api.db.UserInfoApi;
import com.tanhua.api.mongo.MovementsApi;
import com.tanhua.api.mongo.RecommendUserApi;
import com.tanhua.db.Question;
import com.tanhua.db.User;
import com.tanhua.db.UserInfo;
import com.tanhua.mongo.RecommendUser;
import com.tanhua.mongo.Visitors;
import com.tanhua.template.HuanXinTemplate;
import com.tanhua.vo.PageBeanVo;
import com.tanhua.vo.TodayBest;
import com.tanhua.vo.UserHolder;
import org.apache.commons.beanutils.BeanUtilsBean;
import org.apache.commons.lang3.RandomUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Service
public class RecommendService {
    @Reference
    private RecommendUserApi recommendUserApi;

    @Reference
    private UserInfoApi userInfoApi;
    @Reference
    private QuestionApi questionApi;
    @Reference
    private MovementsApi movementsApi;

    @Autowired
    private HuanXinTemplate huanXinTemplate;

    public ResponseEntity querryTodayBest() {

        Long id = UserHolder.getUser().getId();
        RecommendUser recommendUser = recommendUserApi.queryWithMaxScore(id);
        if (recommendUser == null) {
            recommendUser = new RecommendUser();
            recommendUser.setUserId(2L);
            recommendUser.setScore(99.0);
        }
        UserInfo userInfo = userInfoApi.findByUserId(recommendUser.getUserId());

        TodayBest todayBest = new TodayBest();
        BeanUtils.copyProperties(userInfo, todayBest);
        if (userInfo.getTags() != null) {
            todayBest.setTags(userInfo.getTags().split(","));
        }
        todayBest.setFateValue((recommendUser.getScore().longValue()));
        System.out.println(todayBest);
        return ResponseEntity.ok(todayBest);

    }

    public ResponseEntity todayBestList(Integer page, Integer pagesize) {
        Long id = UserHolder.getUser().getId();
        PageBeanVo pageBeanVo = recommendUserApi.queryTodayBestList(id, page, pagesize);
        List<RecommendUser> items = (List<RecommendUser>) pageBeanVo.getItems();


        // 如果该登录用户没有推荐人（自己造）
        if (items.size() == 0) {
            items = fromTuiJianRen();
        }


        //将每一个RecommendUSer转换成TodayBest
        ArrayList<TodayBest> todayBestList = new ArrayList<>();
        //4 根据佳人信息获取头像 昵称封装给List<TodayBest>
        for (RecommendUser recommendUser : items) {
            TodayBest todayBest = new TodayBest();
            UserInfo userInfo = userInfoApi.findByUserId(recommendUser.getUserId());
            //封装成TodayBest
            BeanUtils.copyProperties(userInfo, todayBest);
            todayBest.setFateValue(recommendUser.getScore().longValue());
            todayBest.setTags(userInfo.getTags().split(","));
            todayBestList.add(todayBest);
        }
        // 封装app需要用的pageBeanVo
        pageBeanVo.setItems(todayBestList);
        pageBeanVo.setPage(page);
        pageBeanVo.setPagesize(pagesize);

        //返回vo
        return ResponseEntity.ok(pageBeanVo);
    }

    //如果没有推荐人，则生成。
    private List<RecommendUser> fromTuiJianRen() {
        ArrayList<RecommendUser> list = new ArrayList<>();
        for (Long i = 1L; i < 10; i++) {
            RecommendUser recommendUser = new RecommendUser();
            recommendUser.setUserId(i);
            recommendUser.setScore(RandomUtils.nextDouble(60, 99));
            list.add(recommendUser);
        }
        return list;
    }

    public ResponseEntity querryPersonalInfo(Long jRid) {
        //查询佳人信息
        UserInfo userInfo = userInfoApi.findByUserId(jRid);
        //新建todayBest
        TodayBest todayBest = new TodayBest();
        //封装userInfo到todayBest
        BeanUtils.copyProperties(userInfo, todayBest);
        todayBest.setTags(userInfo.getTags().split(","));//设置标签
        //查询缘分值
        Long score = recommendUserApi.findScore(jRid, UserHolder.getUser().getId());
        todayBest.setFateValue(score);
        //插入访问记录
        Visitors visitors = new Visitors();
        visitors.setFrom("首页"); // 访问来源
        visitors.setUserId(jRid);//佳人
        visitors.setVisitorUserId(UserHolder.getUser().getId()); // 访客

        visitors.setScore((double)score); // 缘分值
        visitors.setDate(System.currentTimeMillis()); // 访问时间
        Long userId = UserHolder.getUser().getId();
        //自己查看自己动态不添加访问记录
        if (jRid != userId){
            movementsApi.save(visitors);
        }

        return ResponseEntity.ok(todayBest);

    }

    public ResponseEntity strangerQuestions(Long userId) {
        Question question = questionApi.findByUserId(userId);
        if (question == null) {
            question = new Question();
            question.setStrangerQuestion("今晚约吗");
        }
        String strangerQuestion = question.getStrangerQuestion();
        return ResponseEntity.ok(strangerQuestion);
    }

    public ResponseEntity toStrangerQuestions(Long jRId, String reply) {
        Long userId = UserHolder.getUser().getId();
        UserInfo userInfo = userInfoApi.findByUserId(userId);
        Question question = questionApi.findByUserId(jRId);
        if (question == null) {
            question = new Question();
            question.setStrangerQuestion("今晚约吗");
        }
        HashMap<String, String> map = new HashMap<>();
        map.put("userId", userId.toString());
        map.put("nickname", userInfo.getNickname());
        map.put("strangerQuestion", question.getStrangerQuestion());
        map.put("reply", reply);

        String jsonString = JSON.toJSONString(map);
        huanXinTemplate.sendMsg(jRId.toString(),jsonString);
        return ResponseEntity.ok(null);
    }
}
